<template>
    <div class="login">
        <section class="form-container">
            <h1 class="login-logo animate__animated animate__lightSpeedInLeft">ERP登录</h1>
            <div class="login-form-wrap">
                <el-form :model="loginUser" :rules="rules" ref="loginForm">
                    <el-form-item
                        prop="name"
                        class="animate__animated animate__fadeInRight"
                        style="margin-bottom: 24px"
                    >
                        <el-input
                            @focus="handleChange('name')"
                            @keyup.enter.native="submitForm('loginForm')"
                            size="default"
                            v-model="loginUser.name"
                            placeholder="请输入用户名"
                        ></el-input>
                    </el-form-item>
                    <el-form-item
                        prop="password"
                        class="animate__animated animate__fadeInLeft"
                        style="margin-bottom: 24px"
                    >
                        <el-input
                            @focus="handleChange('password')"
                            @keyup.enter.native="submitForm('loginForm')"
                            size="default"
                            v-model="loginUser.password"
                            placeholder="请输入密码"
                            type="password"
                            :show-password="true"
                        ></el-input>
                    </el-form-item>
                    <el-form-item class="animate__animated animate__fadeInRight">
                        <el-button class="login-button" size="default" type="primary" @click="submitForm('loginForm')"
                            >登 录</el-button
                        >
                    </el-form-item>
                </el-form>
            </div>
        </section>
    </div>
</template>

<script>
import {postLogin, getCodeWeb} from '@/api/login';
import permission from '@/permission'; // 权限管理
import {mapMutations} from 'vuex';
import store from '@/store/index';
import {HOME} from '@/router/route-name';

export default {
    name: 'login',
    async beforeRouteEnter(to, from, next) {
        // 如果token不存在，那么跳转登录页面
        if (!store.state.user.userToken) {
            next();
        } else {
            next('/home');
        }
    },
    data() {
        const validatorEmail = (rule, value, callback) => {
            if (this.validatorErrors.email) {
                return callback(this.validatorErrors.email);
            }
            callback();
        };
        const validatorPassword = (rule, value, callback) => {
            if (this.validatorErrors.password) {
                return callback(this.validatorErrors.password);
            }
            callback();
        };
        const validatorCode = (rule, value, callback) => {
            if (this.validatorErrors.code) {
                return callback(this.validatorErrors.code);
            }
            callback();
        };
        return {
            HOME,
            loginUser: {
                name: '',
                password: '',
                code: '',
                login_id: ''
            },
            // 记录那些字段有错误
            validatorErrors: {
                name: '',
                password: '',
                code: ''
            },
            codeImgURL: '', // 验证码URL
            rules: {
                name: [{required: true, message: '用户名不能为空', trigger: 'change'}],
                password: [
                    {required: true, message: '密码不能为空', trigger: 'change'},
                    {validator: validatorPassword, trigger: 'change'}
                ]
            }
        };
    },

    methods: {
        ...mapMutations({
            setUserToken: 'user/setUserToken',
            setUserInfo: 'user/setUserInfo'
        }),
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (!valid) {
                    return;
                }
                const {code, name, password, login_id: loginId} = this.loginUser;
                const newItem = {name, password};

                // 清除token
                postLogin(newItem).then(async ({data: res}) => {
                    switch (res.status) {
                        case 200:
                            // 登录成功
                            const {token, name, email} = res.data || {};

                            // 设置用户token
                            // 将token等信息，存储到本地
                            this.setUserToken(token);
                            this.setUserInfo({name, email});

                            await permission();
                            // 页面跳转
                            this.$router.replace({name: HOME});
                            break;
                        case 4011:
                            // 验证码输入错误
                            this.validatorErrors.code = '验证码输入错误';
                            break;
                        case 4022:
                            // 用户名或密码错误
                            this.validatorErrors.name = '用户名或密码错误';
                            this.validatorErrors.password = '用户名或密码错误';
                            break;

                        default:
                            this.$message({showClose: true, type: 'success', message: res.message});
                            break;
                    }
                    if (res.status !== 200) {
                        this.$refs[formName].validate();
                        // this.getCodeWeb();
                    }
                });
            });
        },
        handleChange(name) {
            if (name === 'name') {
                this.validatorErrors['password'] = undefined;
                if (this.validatorErrors['password']) {
                    this.$refs['loginForm'].validateField(['password']);
                }
            }
            if (name === 'password') {
                this.validatorErrors['name'] = undefined;
                if (this.validatorErrors['name']) {
                    this.$refs['loginForm'].validateField(['name']);
                }
            }
            if (this.validatorErrors[name]) {
                this.validatorErrors[name] = undefined;
            }
        }
    }
};
</script>
<style lang="scss">
.login {
    .el-input__inner {
        height: 44px;
        line-height: 44px;
    }
    .login-button {
        font-size: 14px;
        padding: 14px 20px;
    }
}
</style>

<style scoped lang="scss">
@import '@/styles/variables.scss';
.login {
    width: 100vw;
    height: 100%;
    overflow: hidden;
    background-color: $--color-border-normal;
    background-size: 100% 100%;
    text-align: center;
    padding-bottom: 20px;
    box-sizing: border-box;
}
.form-container .login-logo {
    padding-top: 15vh;
    margin-bottom: 28px;
    font-size: 36px;
}
.form-container .login-form-wrap {
    max-width: 400px;
    margin: 0 auto;
    padding: 0 40px 40px 40px;
    background-color: transparent;
    box-sizing: border-box;
    border-radius: 4px;

    .login-form-title {
        padding: 24px 0;
        color: #000;
        font-size: 18px;
    }

    .login-button {
        display: block;
        width: 100%;
    }
}

@media screen and (max-width: 350px) {
    .form-container {
        .login-form-wrap {
            padding: 0 20px 20px 20px;
        }
    }
}
</style>
